package ru.usu.gv.uicomponents.viewitems.edge;

import com.sun.j3d.utils.geometry.Cylinder;

import ru.usu.gv.styles.StyleFacade;
import ru.usu.gv.uicomponents.UIElementBase;
import ru.usu.gv.uicomponents.UIVertex;
import ru.usu.gv.uicomponents.viewitems.ViewItemBase;

import javax.media.j3d.Appearance;
import javax.media.j3d.Geometry;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.AxisAngle4d;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;

import java.awt.Color;

/**
 * @author spupyrev
 * 24.10.2009
 */
public class TubeEdgeView extends ViewItemBase implements IEdgeViewItem
{
	private UIVertex v1;
	private UIVertex v2;
	private Cylinder cylinder;
	private double width;

	TransformGroup transformGroup;

	public TubeEdgeView(Appearance appearance, TransformGroup tg, UIVertex v1, UIVertex v2)
	{
		super(tg, appearance, appearance.getMaterial());

		this.v1 = v1;
		this.v2 = v2;

		float radius = (float) StyleFacade.getEdgeRadius();
		cylinder = new Cylinder(radius, 1.0f, appearance);
		width = 1.0;
		transformGroup = new TransformGroup();
		transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
		transformGroup.addChild(cylinder);

		tg.addChild(transformGroup);
	}

	public Geometry buildGeometry()
	{
		Transform3D t = new Transform3D();
		//scale
		double length = v1.getPosition().distance(v2.getPosition());
		if (length < 0.01)
			length = 0.01;
		Vector3d scale = new Vector3d(width, length, width);
		t.setScale(scale);

		Vector3d center = new Vector3d(v1.getPosition());
		center.add(v2.getPosition());
		center.scale(0.5);
		//translation
		t.setTranslation(center);

		Vector3d vec1 = new Vector3d();
		vec1.sub(v1.getPosition(), v2.getPosition());
		Vector3d vec2 = new Vector3d(0, 2, 0);

		Vector3d norm = new Vector3d();
		norm.cross(vec2, vec1);
		AxisAngle4d axisAngle4d = new AxisAngle4d(norm.x, norm.y, norm.z, vec2.angle(vec1));
		//rotation
		t.setRotation(axisAngle4d);

		transformGroup.setTransform(t);

		return null;
	}

	@Override
	public void setColor(Color color)
	{
		super.setColor(color);
		getMaterial().setDiffuseColor(new Color3f(color));
	}

	public void makePickable(UIElementBase ge)
	{
		ge.makePickable(cylinder.getShape(Cylinder.BODY));
		ge.makePickable(cylinder.getShape(Cylinder.BOTTOM));
		ge.makePickable(cylinder.getShape(Cylinder.TOP));
	}

	public double getWidth()
	{
		return width;
	}

	public void setWidth(double width)
	{
		this.width = width;
	}

	public Point3d[] getControlPoints()
	{
		return new Point3d[] {};
	}

	public void moveToCanvasPosition(TransformGroup transformGroup, int x, int y)
	{
		// pass
	}

	public void rectificate()
	{
		// pass
	}

	public void setControlPoints(Point3d[] controlPoints)
	{
		// pass
	}

}
